<div id="options">
    <div class="row-fluid">
        <div class="span4">开机自动启动</div> <!-- .span4 -->
        <div class="span8">
            <input id="auto-start" type="checkbox" data-toggle="switch" />
        </div> <!-- .span8 -->
    </div> <!-- .row-fluid -->
    <div class="row-fluid">
        <div class="span4">启动时弹出状态页</div> <!-- .span4 -->
        <div class="span8">
            <input id="popup-webui" type="checkbox" data-toggle="switch" />
        </div> <!-- .span8 -->
    </div> <!-- .row-fluid -->
    <div class="row-fluid">
        <div class="span4">
            <label for="update-options" class="pull-down-control">
                <i class="icon icon-chevron-right"></i> 升级管理
            </label>
        </div> <!-- .span4 -->
    </div> <!-- .row-fluid -->
    <div id="update-options" style="display: none;">
        <hr>
        <div class="row-fluid">
            <div class="span3">
                <label for="check-update">自动升级到：<a href="https://github.com/XX-net/XX-Net/wiki/Auto-update" target="_blank">(帮助)</a></label>
            </div>
            <div class="span6">
                <select id="check-update">
                    <option value="dont-check">不升级</option>
                    <option value="long-term-stable">长期稳定版</option>
                    <option value="stable">稳定版</option>
                    <option value="test">测试版</option>
                </select>
            </div>
            <div class="span2">
                <button class="btn btn-primary ladda-button" data-style="slide-up" id="check-new-version">检查最新版本</button>
            </div>
            <div class="span1" id="check-new-version-process">
            </div>
        </div> <!-- .row-fluid -->
        <div class="row-fluid version-line hide">
            <div class="span2">
                <label for="current-version-no">当前版本：</label>
            </div>
            <div class="span4" id="current-version-no" style="margin-top:10px">
            </div>
        </div> <!-- .row-fluid -->
        <div class="row-fluid version-line hide">
            <div class="span2">
                <label for="test-version-no">测试版版本：</label>
            </div>
            <div class="span4" id="test-version-no" style="margin-top:10px">
            </div>
            <div class="span2" >
                <button class="btn btn-warning update-button ladda-button" data-style="expand-right" id="update-test-version">立即更新</button>
            </div>
        </div> <!-- .row-fluid -->
        <div class="row-fluid version-line hide">
            <div class="span2">
                <label for="stable-version-no">稳定版版本：</label>
            </div>
            <div class="span4" id="stable-version-no" style="margin-top:10px">
            </div>
            <div class="span2">
                <button class="btn btn-primary update-button ladda-button" data-style="expand-right" id="update-stable-version">立即更新</button>
            </div>
        </div> <!-- .row-fluid -->
        <hr>
    </div> <!-- #advanced-options -->
    <div class="row-fluid">
        <div class="span4">
            <label for="modules-manager" class="pull-down-control">
                <i class="icon icon-chevron-right"></i> 模块管理
            </label>
        </div> <!-- .span4 -->
    </div> <!-- .row-fluid -->
    <div id="modules-manager" style="display: none;">
        <hr>
        <div class="row-fluid">
            <div class="span4">启用Goagent</div> <!-- .span4 -->
            <div class="span8">
                <input id="goagent-enable" type="checkbox" data-toggle="switch" />
            </div> <!-- .span8 -->
        </div> <!-- .row-fluid -->
        <div class="row-fluid">
            <div class="span4">启用PHP代理</div> <!-- .span4 -->
            <div class="span8">
                <input id="php-enable" type="checkbox" data-toggle="switch" />
            </div> <!-- .span8 -->
        </div> <!-- .row-fluid -->
        <hr>
    </div> <!-- #advanced-options -->
</div> <!-- #options -->

<!-- JavaScript -->
<script type="text/javascript">
    title('系统配置选项');
</script>
<script type="text/javascript">
    $(function() {
        $('[data-toggle=switch]').wrap('<div class="switch" />').parent().bootstrapSwitch();
    });
</script>
<script type="text/javascript">
    $(function() {
        getStatus();
    });
</script>
<script type="text/javascript">
    function getStatus() {
        var pageRequests = {
            'cmd': 'get_config'
        };

        $.ajax({
            type: 'GET',
            url: '/config',
            data: pageRequests,
            dataType: 'JSON',
            success: function(result) {
                if ( result['auto_start'] != 0 ) {
                    $( "#auto-start").parent().removeClass('switch-off');
                    $( "#auto-start").parent().addClass('switch-on');

                    $( "#auto-start").prop('checked', true);
                }
                if ( result['popup_webui'] != 0 ) {
                    $( "#popup-webui").parent().removeClass('switch-off');
                    $( "#popup-webui").parent().addClass('switch-on');

                    $( "#popup-webui").prop('checked', true);
                }
                if ( result['goagent_enable'] != 0 ) {
                    $( "#goagent-enable").parent().removeClass('switch-off');
                    $( "#goagent-enable").parent().addClass('switch-on');


                    $( "#goagent-enable").prop('checked', true);
                }
                if ( result['php_enable'] != 0 ) {
                    $( "#php-enable").parent().removeClass('switch-off');
                    $( "#php-enable").parent().addClass('switch-on');

                    $( "#php-enable").prop('checked', true);
                }
                $( "#check-update").val(result['check_update']);
            },
            error: function() {
                displayErrorMessage();
            }
        });
    }
</script>
<script type="text/javascript">
    $('.pull-down-control').click(function() {
        var isShown = $('i.icon', this).hasClass('icon-chevron-down');
        var id = $(this).attr('for');

        if ( !isShown ) {
            $('i.icon', this).removeClass('icon-chevron-right');
            $('i.icon', this).addClass('icon-chevron-down');
            $('#'+id).slideDown();
        } else {
            $('i.icon', this).removeClass('icon-chevron-down');
            $('i.icon', this).addClass('icon-chevron-right');
            $('#'+id).slideUp();
        }
    });
</script>
<script type="text/javascript">
    $('#auto-start').change(function() {
        var isChecked = $(this).is(':checked'),
            key       = 'auto_start',
            value     = isChecked ? 1 : 0;

        return setConfig(key, value);
    });

    $('#check-update').change(function() {
        var key   = 'check_update',
            value = $(this).val();

        return setConfig(key, value);
    });

    $('#popup-webui').change(function() {
        var isChecked = $(this).is(':checked'),
            key       = 'popup_webui',
            value     = isChecked ? 1 : 0;

        return setConfig(key, value);
    });

    $('#goagent-enable').change(function() {
        var isChecked = $(this).is(':checked'),
            key       = 'goagent_enable',
            value     = isChecked ? 1 : 0;

        setConfig(key, value);
    });

    $('#php-enable').change(function() {
        var isChecked = $(this).is(':checked'),
            key       = 'php_enable',
            value     = isChecked ? 1 : 0;

        setConfig(key, value);
    });
</script>
<script type="text/javascript">
    function setConfig(key, value) {
        var pageRequests = {};

        pageRequests['cmd'] = 'set_config';
        pageRequests[key]   = value;

        $.ajax({
            type: 'GET',
            url: '/config',
            data: pageRequests,
            dataType: 'JSON',
            success: function(result) {
                if ( result['res'] == 'success' ) {
                    if ( key == 'goagent_enable' || key == 'php_enable' ) {
                        restartingService(key);
                    } else {
                        tip('设置已成功保存.', 'success');
                    }

                } else {
                    displayErrorMessage();
                }
            },
            error: function() {
                displayErrorMessage();
            }
        });
    }
</script>
<script type="text/javascript">
    function displayErrorMessage() {
        tip('发生未知错误, 请刷新页面重试.', 'error');
    }
</script>
<script type="text/javascript">
    function restartingService(serviceNameSlug) {
        var serviceName     = '',
            restatingTime   = 5,
            messageTemplate = '正在重启服务[%s], 页面将在%s秒内刷新.';

        if ( serviceNameSlug == 'goagent_enable' ) {
            serviceName     = 'GoAgent';
        } else if ( serviceNameSlug == 'php_enable' ) {
            serviceName     = 'PHP代理';
        } else {
            serviceName     = 'Unknown';
        }

        tip(messageTemplate.format(serviceName, restatingTime), 'warning');

        setTimeout(function () {
            location.reload();
        }, restatingTime * 1000);
    }
</script>
<script type="text/javascript">
function versionCompare(v1, v2, options) {
    var lexicographical = options && options.lexicographical,
        zeroExtend = options && options.zeroExtend,
        v1parts = v1.split('.'),
        v2parts = v2.split('.');

    function isValidPart(x) {
        return (lexicographical ? /^\d+[A-Za-z]*$/ : /^\d+$/).test(x);
    }

    if (!v1parts.every(isValidPart) || !v2parts.every(isValidPart)) {
        return NaN;
    }

    if (zeroExtend) {
        while (v1parts.length < v2parts.length) v1parts.push("0");
        while (v2parts.length < v1parts.length) v2parts.push("0");
    }

    if (!lexicographical) {
        v1parts = v1parts.map(Number);
        v2parts = v2parts.map(Number);
    }

    for (var i = 0; i < v1parts.length; ++i) {
        if (v2parts.length == i) {
            return 1;
        }

        if (v1parts[i] == v2parts[i]) {
            continue;
        }
        else if (v1parts[i] > v2parts[i]) {
            return 1;
        }
        else {
            return -1;
        }
    }

    if (v1parts.length != v2parts.length) {
        return -1;
    }

    return 0;
}
    $('#check-new-version').click(function(){
        var loading = Ladda.create(this);
        loading.start();

        var pageRequests = {};
        pageRequests['cmd'] = 'get_new_version';

        $.ajax({
            type: 'GET',
            url: '/config',
            data: pageRequests,
            dataType: 'JSON',
            success: function(result) {
                if ( result['res'] == 'success' ) {
                    createVerInfo(result);

                    $('.version-line').removeClass('hide');
                    $('.alert').removeClass('alert-error').addClass('hide');
                } else {
                    displayErrorMessage();
                }
                $('#check-new-version-process').addClass('hide');
            },
            error: function() {
                displayErrorMessage();
                $('#check-new-version-process').addClass('hide');
            },
            complete: function () {
                loading.stop();
            }
        });
    });
</script>

<script type="text/javascript">
    var dtd         = $.Deferred();
    var configUrl   = '/config?cmd=get_new_version';
    var progressUrl = 'download?cmd=get_progress';

    // 检测下载状态
    $.getJSON(progressUrl, function (rst) {
        Object.keys(rst).forEach(function (v) {
            if (rst[v].status === 'downloading' && v.indexOf('XX-Net/zip') > -1) {
                dtd.resolve((v.split('XX-Net/zip/'))[1]);
            }
        });
    });

    // 展示下载状态
    dtd.promise().done(function (ver) {
        $.getJSON(configUrl, function(rst) {
            createVerInfo(rst);

            $('#check-new-version').hide();
            $('#update-options').slideDown('fast', function() {
                $('.version-line').slideDown('fast');

                showDownloadProgress(ver);
            });
        });
    });

    $('.update-button').click(function(){
        var pageRequests = {};
        pageRequests['cmd'] = 'update_version';

        var id = $(this).attr('id');
        if(id == 'update-test-version'){
            pageRequests['version'] = $('#test-version-no').html();
        }else if(id == 'update-stable-version'){
            pageRequests['version'] = $('#stable-version-no').html();
        }

        var ver = $(this).attr('data-ver');
        showDownloadProgress(ver);

        $.ajax({
            type: 'GET',
            url: '/config',
            data: pageRequests,
            dataType: 'JSON',
            success: function(result) {
                if ( result['res'] == 'success' ) {
                    tip('更新进行中。。。.', "info");
                } else {
                    displayErrorMessage();
                }
                $('#check-new-version-process').addClass('hide');
            },
            error: function() {
                displayErrorMessage();
                $('#check-new-version-process').addClass('hide');
            }
        });
    });


    /**
     * 生成版本信息
     * @param rst 来自 url /config 的json
     */
    function createVerInfo (rst) {
        var $updateTestVersion = $('#update-test-version');
        var $updateStableVersion = $('#update-stable-version');

        var testVersion = rst['test_version'];
        var stableVersion = rst['stable_version'];
        var currentVersion = rst['current_version'];

        $updateTestVersion.attr('data-ver', testVersion);
        $updateStableVersion.attr('data-ver', stableVersion);

        $('#current-version-no').html(currentVersion);
        $('#test-version-no').html(testVersion);
        $('#stable-version-no').html(stableVersion);

        if(versionCompare(testVersion, currentVersion) <= 0){
            $updateTestVersion.addClass("hide");
        }
        if(versionCompare(stableVersion, currentVersion) <= 0){
            $updateStableVersion.addClass("hide");
        }
    }


    /**
     * 展示按钮的下载状态
     * @param ver
     */
    function showDownloadProgress (ver) {
        var $btn = $('.update-button')
                .add('#check-new-version').hide()
                .filter('[data-ver="'+ ver +'"]').show();

        $btn.text('正在更新中..');

        var loading = Ladda.create($btn[0]);
        loading.start();

        getDownloadProgress(ver, function (status, progress) {
            switch (status) {
                case 'downloading':
                    loading.setProgress(progress);
                    break;

                case 'finished':
                    loading.setProgress(progress);
                    loading.stop();

                    $btn.text('更新完毕').prop('disabled', true);
                    break;

                default:
                    loading.stop();

                    $btn.text('发生未知错误');
            }
        });
    }


    /**
     * 轮询获取下载进度
     * @param ver
     * @param cb(status, progress)
     * @param [delay = 500] 延迟时间
     */
    function getDownloadProgress (ver, cb, delay) {
        var progressUrl = 'download?cmd=get_progress',
            verUrl      = 'https://codeload.github.com/XX-net/XX-Net/zip/' + ver;

        setTimeout(function () {
            $.getJSON(progressUrl, function(rst) {
                var data = rst[verUrl];

                switch (data.status) {
                    case 'downloading':
                        cb('downloading', +data.downloaded / +data.size);

                        getDownloadProgress(ver, cb, delay);
                        break;

                    case 'finished':
                        cb('finished', 1);
                        break;

                    default:
                    // do nothing
                }
            });
        }, delay || 500);
    }
</script>

